package com.mvc.interceptor;

import com.mvc.DispatchServlet;
import com.mvc.ResponseUtil;
import com.peanut.entity.JsonResult;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.InvocationTargetException;

@Slf4j
public class ExceptionInterceptor implements HandlerInterceptor{
	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Exception ex) throws Exception {
		if(ex != null){
			Throwable f = ex;
			if(ex instanceof InvocationTargetException){
				f = ((InvocationTargetException) ex).getTargetException();
			}
			
			log.error("发生异常! 记录日志......↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓");
			log.error(f.getMessage());
			log.error(String.valueOf(f.getCause()));
			log.error("错误类:{} 方法:{} 行数:{}",
					f.getStackTrace()[0].getClassName(),
					f.getStackTrace()[0].getMethodName(),
					f.getStackTrace()[0].getLineNumber());
			
			if(f instanceof NullPointerException){
				JsonResult fail = JsonResult.fail(2000,"空指针异常，需要开发进行代码检查");
				ResponseUtil.ServerError2(response,fail);
			}else{
				String message = f.getMessage();
				JsonResult fail = JsonResult.fail(message);
				ResponseUtil.ServerError2(response,fail);
			}
		}
	}
}
